<template>
  <view>
    <view class="tip" v-if="userTrendList.length<=0">你还没有发表作品哦~</view>
    <view class="trend-box" v-for="(item, i) in modifiedTrendList" :key="i" v-else>
      <uni-card :title="item.nickName" :sub-title="item.createTime" :thumbnail="item.avatarUrl" :border="false"
        shadow="0px 1px 2px 0.1px #eee" :extra="item.position ? item.position : null">
        <view class="image-box" v-if="item.imageList.length > 1">
          <view class="image-item" v-for="(item2, i2) in item.imageList" :key="i2">
            <image class="image-img" @click="preview(i2, item.imageList)" mode="aspectFill" :src="item2"></image>
          </view>
        </view>

        <image class="image-box-img" style="width: 100%;" mode="widthFix" :src="item.imageList"
          v-if="item.imageList.length === 1"></image>
        <text class="uni-body uni-mt-5">{{item.content}}</text>
        <view slot="actions" class="card-actions">
          <view class="card-actions-item" @click="deleteMyTrendItem(i)">
            <uni-icons class="card-actions-item-icon" type="trash" size="18" color="#999"></uni-icons>
            <text class="card-actions-item-text">删除</text>
          </view>
          <view class="card-actions-item" @click="likeTrend(item, i)">
            <uni-icons type="heart" size="18" color="#999" v-if="!item.isLiked"></uni-icons>
            <uni-icons type="heart-filled" size="18" color="#fba007" v-else></uni-icons>
            <text class="card-actions-item-number">{{ formatLikes(item.likeNum) }}</text>
          </view>
          <view class="card-actions-item" @click="commentTrend">
            <uni-icons type="chatbubble" size="18" color="#999"></uni-icons>
            <text class="card-actions-item-text">评论</text>
          </view>
        </view>
      </uni-card>
    </view>
    <view class="topping-icon" v-show="showTopBtn" @click="scrollToTop">
      <image src="../../static/stop_imgs/topping.png"></image>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    computed: {
      ...mapState('m_trend', ['trendList']),
      ...mapState('m_user', ['userinfo', 'userTrendList', 'userLikeTrendList']),
    },
    components: {},
    data() {
      return {
        modifiedTrendList: [],
        // 置顶按钮显示隐藏标志
        showTopBtn: false,
      };
    },
    onLoad() {
      this.getUserTrendList()
      this.getTrendList()
    },
    // 监听页面滚动事件
    onPageScroll(e) {
      if (e.scrollTop > 0) {
        this.showTopBtn = true
      } else {
        this.showTopBtn = false
      }
    },
    methods: {
      ...mapMutations('m_user', ['updateUserTrendList', 'updateUserLikeTrendList', 'deleteUserLikeTrendListItem',
        'addUserTrendListLikeNum', 'deleteUserTrendListLikeNum'
      ]),
      ...mapMutations('m_trend', ['updateTrendList', 'addTrendListLikeNum', 'deleteTrendListLikeNum']),

      // 获取动态列表
      getUserTrendList() {

        const newUserTrendList = this.userTrendList.map(trend => {
          const isLiked = this.userLikeTrendList.some(likeTrend => likeTrend.createTime === trend.createTime);
          return {
            ...trend,
            isLiked: isLiked
          };
        });
        // 将 createTime 参数转换为时间差字符串
        const modifiedTrendList = newUserTrendList.map(trend => {
          return {
            ...trend,
            createTime: this.getRelativeTime(trend.createTime)
          };
        });
        this.modifiedTrendList = modifiedTrendList
        console.log(this.modifiedTrendList)
      },

      // 计算并格式化动态的点赞值
      formatLikes(likeNum) {
        if (likeNum >= 10000) {
          return (likeNum / 10000).toFixed(1) + 'w';
        } else if (likeNum >= 1000) {
          return (likeNum / 1000).toFixed(1) + 'k';
        } else {
          return likeNum.toString();
        }
      },
      //计算动态创建时间和当下时间的距离
      getRelativeTime(time) {
        const target = new Date(time);
        const now = new Date();

        const diff = now - target;

        const seconds = Math.floor(diff / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);
        const months = Math.floor(days / 30);
        const years = Math.floor(months / 12);

        if (years > 0) {
          return years + '年前';
        } else if (months > 0) {
          return months + '月前';
        } else if (days > 0) {
          return days + '天前';
        } else if (hours > 0) {
          return hours + '小时前';
        } else if (minutes > 0) {
          return minutes + '分钟前';
        } else if (seconds > 10) {
          return seconds + '秒前';
        } else {
          return '刚刚';
        }
      },

      onClick(e) {
        console.log(e)
      },
      // 点赞按钮事件
      likeTrend(item,index) {
        const trend = item
        const createTime = this.userTrendList[index].createTime
        var trendLikeNum = trend.likeNum
        if(trend.isPrivacy === true) {
          var likeTrend = this.userTrendList[index]
          if (trend.isLiked === false) {
            trend.isLiked = true
            trend.likeNum++
            trendLikeNum++
          
            const index = this.userLikeTrendList.findIndex(obj => obj.createTime === createTime);
            if (index === -1) {
              this.updateUserLikeTrendListToServer(likeTrend)
              this.updateUserTrendListLikeNumToServer(createTime, trendLikeNum)
            } else {
              return uni.$showMsg('已点赞啦！')
            }
          } else {
            trend.isLiked = false
            trend.likeNum--
            trendLikeNum--
          
            const index = this.userLikeTrendList.findIndex(obj => obj.createTime === createTime);
            if (index !== -1) {
              this.deleteUserLikeTrendListToServer(createTime)
              this.updateUserTrendListLikeNumToServer(createTime, trendLikeNum)
            } else {
              return uni.$showMsg('取消点赞失败！')
            }
          }
        }else {
          const foundObject = this.trendList.find(item => item.createTime === createTime);
          foundObject.likeNum++
          const trendId = foundObject.id
          var trendLikeNum = trend.likeNum
          
          if (trend.isLiked === false) {
            trend.isLiked = true
            trend.likeNum++
            trendLikeNum++
          
            const index = this.userLikeTrendList.findIndex(obj => obj.id === trendId);
            if (index === -1) {
              this.updateUserLikeTrendListToServer(foundObject)
              this.updateTrendListLikeNumToServer(trendId, trendLikeNum)
              this.updateUserTrendListLikeNumToServer(createTime, trendLikeNum)
            } else {
              return uni.$showMsg('已点赞啦！')
            }
          } else {
            trend.isLiked = false
            trend.likeNum--
            trendLikeNum--
          
            const index = this.userLikeTrendList.findIndex(obj => obj.id === trendId);
            if (index !== -1) {
              this.deleteUserLikeTrendListToServer(createTime)
              this.updateTrendListLikeNumToServer(trendId, trendLikeNum)
              this.updateUserTrendListLikeNumToServer(createTime, trendLikeNum)
            } else {
              return uni.$showMsg('取消点赞失败！')
            }
          }
        }

      },
      // 请求服务器更新作品喜欢人数
      async updateTrendListLikeNumToServer(trendId, trendLikeNum) {
        // 准备参数
        const query = {
          trendId,
          trendLikeNum,
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/trendListLikeNum', query)
        console.log('后端返回的发表结果', res)
        if (res.meta.status !== 200) return $showMsg('发表失败')
      },
      // 请求服务器更新用户作品喜欢人数
      async updateUserTrendListLikeNumToServer(createTime, trendLikeNum) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          createTime,
          trendLikeNum,
        };
        const {
          data: res
        } = await uni.$http.post('/api/update/userTrendListLikeNum', query)
        if (res.meta.status !== 200) return uni.$showMsg('更新作品喜欢人数失败')
        this.updateUserTrendList(res.message)
      },


      // 请求服务器更新用户喜欢的作品列表
      async updateUserLikeTrendListToServer(trend) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          trend,
        };
        const {
          data: res
        } = await uni.$http.post('/api/update/likeWorks', query)
        if (res.meta.status !== 200) return uni.$showMsg('更新喜欢作品列表失败')
        this.updateUserLikeTrendList(res.message)
      },
      // 请求服务器删除用户喜欢的作品列表
      async deleteUserLikeTrendListToServer(createTime) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          createTime,
        };
        const {
          data: res
        } = await uni.$http.post('/api/delete/likeWorks', query)
        if (res.meta.status !== 200) return uni.$showMsg('删除喜欢作品列表失败')
        this.updateUserLikeTrendList(res.message)
      },
      // 点击评论按钮事件
      commentTrend() {
        return uni.$showMsg('待开发中')
      },

      // 删除作品事件
      deleteMyTrendItem(index) {
        const obj = this.userTrendList[index];
        const createTime = obj.createTime;
        const isPrivacy = obj.isPrivacy
        console.log(index)
        console.log(obj)

        uni.showModal({
          title: '提示',
          content: '确认删除作品吗？'
        }).then(res => {
          if (res[1].confirm) {
            if (isPrivacy === false) {
              this.deleteTrendItemToServer(createTime)
              this.deleteUserTrendItemToServer(createTime)
            } else {
              this.deleteUserTrendItemToServer(createTime)
            }
          } else if (res[1].cancel) {}
        });
      },
      // 向服务器发送请求删除作品列表作品项
      async deleteTrendItemToServer(trendCreateTime) {
        const query = {
          trendCreateTime,
        };
        const {
          data: res
        } = await uni.$http.post('/api/delete/works', query)
        if (res.meta.status !== 200) return uni.$showMsg('删除作品失败')
        this.updateTrendList(res.message)
      },
      // 向服务器发送请求删除用户作品列表作品项
      async deleteUserTrendItemToServer(trendCreateTime) {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          trendCreateTime,
        };
        const {
          data: res
        } = await uni.$http.post('/api/delete/userWorks', query)
        if (res.meta.status !== 200) return uni.$showMsg('删除作品失败')
        this.updateUserTrendList(res.message)
        this.getUserTrendList()
      },
      
      // 获取动态列表
      async getTrendList() {
        const {
          data: res
        } = await uni.$http.post('/api/get/trendWorks')
        console.log('后端返回的动态获取结果', res)
        if(res.meta.status !== 200) return $showMsg('动态获取失败')
        console.log('动态获取信息',res.message)
        this.updateTrendList(res.message)
        },
      // 实现轮播图的预览效果
      preview(index, urls) {
        // 调用 uni.previewImage() 方法预览图片
        uni.previewImage({
          // 预览时，默认显示图片的索引
          current: index,
          // 所有图片 url 地址的数组
          urls,
        })
      },
      // 点击置顶按钮回到顶部事件
      scrollToTop() {
        if(this.showTopBtn === true) {
          uni.pageScrollTo({
            scrollTop: 0,
            duration: 0
          })
        }
      },
    }
  }
</script>

<style lang="scss">
  page {
    padding-bottom: 1rpx;
  }
  .tip {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #ccc;
      font-size: 34rpx;
  }
  .trend-box {

    .image-box {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10rpx;
      // border: 1px solid red;

      .image-item {
        width: 200rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-top: 10rpx;
        margin-left: 1rpx;

        .image-img {
          width: 195rpx;
          height: 195rpx;
          background: whitesmoke;
          border-radius: 10rpx;
        }
      }
    }

    .image-box-img {
      background: whitesmoke;
      border-radius: 10rpx;
    }

    .card-actions {
      height: 42px;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      align-items: center;
      // border: 1px solid red;
      // border-top: 1px #DCDCDC solid;
      border-top: 1px #eee solid;

      // padding: 10px 0;
      .card-actions-item {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;

        .card-actions-item-icon {
          // top: 2px;
          text-align: center;
          // border: 1px solid red;
          // padding-top: 5px;
        }

        .card-actions-item-text {
          font-size: 12px;
          color: #6a6a6a;
          text-align: center;
          font-weight: 400;
          margin-left: 5px;

        }

        .card-actions-item-number {
          font-size: 12px;
          color: #6a6a6a;
          text-align: center;
          font-weight: 400;
          margin-left: 5px;
          margin-top: 3rpx;
        }
      }
    }
  }
  .topping-icon {
    width: 38px;
    height: 38px;
    position: sticky;
    bottom: 8px;
    z-index: 999;
    border: 1px solid #ccc;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    float: right;
    margin-right: 8px;
  
    image {
      width: 22px;
      height: 22px;
    }
  }
</style>